/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.gui.sales;

import com.kimstore.bean.Item;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import org.jdesktop.swingx.sort.RowFilters;

/**
 *
 * @author Administrator
 */
public class SelectItemWindowX extends javax.swing.JFrame {

    private SelectItemControllerX selectItemController;

    /**
     * Creates new form SelectProductWindow
     */
    public SelectItemWindowX(SelectItemControllerX selectItemController) {
        initComponents();

        itemsTable.getTableHeader().setReorderingAllowed(false);
        this.selectItemController = selectItemController;
    }

    public void displayWindow() {
        this.setIconImage(Toolkit.getDefaultToolkit().getImage("src/com/kimstore/resources/images/logo.png"));
        prepareUserInterface();
        bindElements();

        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    public void populateTable(List<Item> items) {
        ArrayList<Object[]> objects = new ArrayList<Object[]>();

        for (Item i : items) {
            objects.add(new Object[]{i.getSerial(), i.getProduct().getName(), i.getProduct().getBasePrice()});
        }

        DefaultTableModel tableModel = (DefaultTableModel) itemsTable.getModel();

        for (Object[] o : objects) {
            tableModel.insertRow(tableModel.getRowCount(), o);
        }
    }

    private void prepareUserInterface() {
        searchField.setPrompt("Search Products and SKU");
        itemsTable.setShowGrid(true, true);
        itemsTable.addHighlighter(HighlighterFactory.createSimpleStriping());
    }

    private void bindElements() {
        searchField.setCancelAction(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                searchField.setText("");
                filterTable();
            }
        });

        searchField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent evt) {
                filterTable();
            }
        });
    }

    private void filterTable() {
        Pattern p = Pattern.compile(searchField.getText() + ".*", Pattern.CASE_INSENSITIVE);

        List filters = new ArrayList();
        filters.add(RowFilters.regexFilter(p, 0, 1));

        itemsTable.setRowFilter(RowFilter.andFilter(filters));
    }

    private void selectItem() {
        int rowIndex = itemsTable.getSelectedRow();
        String sku = itemsTable.getValueAt(rowIndex, 0).toString();

        selectItemController.fromWindow(sku);
        
        this.dispose();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        itemsTable = new org.jdesktop.swingx.JXTable();
        searchField = new org.jdesktop.swingx.JXSearchField();
        doneButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Select Item");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/kimstore/resources/images/select-product.png"))); // NOI18N
        jLabel1.setText("Select Item");

        itemsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "SKU", "Product", "Base Price"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(itemsTable);

        doneButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/kimstore/resources/images/done.png"))); // NOI18N
        doneButton.setText("Done");
        doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doneButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/kimstore/resources/images/cancel.png"))); // NOI18N
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(doneButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelButton))
                            .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(doneButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doneButtonActionPerformed
        selectItem();
    }//GEN-LAST:event_doneButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton doneButton;
    private org.jdesktop.swingx.JXTable itemsTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private org.jdesktop.swingx.JXSearchField searchField;
    // End of variables declaration//GEN-END:variables
}
